<template>
  <ContentWrap>
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">检验信息</span>
          <div class="right-button">
            <el-button type="primary" v-if="formData.status != 2 && formData.status !=3"  @click="handleSave(2)">提交审核</el-button>
            <el-button type="primary"  v-if="formData.status != 2 && formData.status !=3" @click="handleSave(1)">保存</el-button>
            <el-button @click="goBack">返回</el-button>
          </div>
        </div>
      </template>

      <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px" class="mt-20px">
        <!-- 项目信息 -->
        <el-card class="mb-4">
          <template #header>
            <div class="text-lg font-bold">基本信息</div>
          </template>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="样品名称" prop="sampleName">
                <el-input v-model="formData.sampleName" disabled placeholder="请输入样品名称" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="样品编号" prop="sampleNum">
                <el-input v-model="formData.sampleNum" disabled placeholder="请输入样品编号" />

                <!-- <el-date-picker
                  v-model="formData.checkStartTime"
                  type="date"
                  placeholder="选择日期"
                  value-format="YYYY-MM-DD"
                /> -->

                <!-- <el-date-picker
        v-model="formData.checkStartTime"
        type="datetime"
        placeholder="请选择项目起始时间"
        value-format="YYYY-MM-DD HH:mm:ss"
      /> -->
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="盲样编号" prop="blindSampleNum">
                <el-input v-model="formData.blindSampleNum" disabled placeholder="请输入盲样编号" />

                <!-- <el-date-picker
                  v-model="formData.checkEndTime"
                  type="date"
                  placeholder="选择日期"
                  value-format="YYYY-MM-DD"
                /> -->

                <!-- <el-date-picker
        v-model="formData.checkEndTime"
        type="datetime"
        placeholder="请选择项目截止日期"
        value-format="YYYY-MM-DD HH:mm:ss"
      /> -->
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="规格型号" prop="model">
                <el-input v-model="formData.model" disabled placeholder="请输入规格型号" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="执行标准" prop="executiveStandard">
                <el-input
                  v-model="formData.executiveStandard"
                  disabled
                  placeholder="请输入执行标准"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="委托单位" prop="entrustCompany">
                <el-input v-model="formData.entrustCompany" disabled placeholder="请输入委托单位" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="受检单位" prop="receiveCheckCompany">
                <el-input
                  v-model="formData.receiveCheckCompany"
                  disabled
                  placeholder="请输入受检单位"
                />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="生产单位" prop="productionCompany">
                <el-input
                  v-model="formData.productionCompany"
                  disabled
                  placeholder="请输入生产单位"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
        <!-- 抽样信息 -->
        <el-card class="mb-4">
          <template #header>
            <div class="text-lg font-bold">抽样信息</div>
          </template>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="抽样地点" prop="samplingSite">
                <el-input v-model="formData.samplingSite" disabled placeholder="请输入抽样地点" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="抽样日期" prop="samplingDate">
                <!-- <el-date-picker
                  v-model="formData.samplingDate"
                  type="date"
                  placeholder="选择日期"
                  value-format="YYYY-MM-DD"
                /> -->

                <el-date-picker
                  disabled
                  style="width: 100%"
                  v-model="formData.samplingDate"
                  type="date"
                  placeholder="请选择抽样日期"
                  format="YYYY-MM-DD "
                  value-format="YYYY-MM-DD "
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="样品批号" prop="sampleBatchNum">
                <el-input disabled v-model="formData.sampleBatchNum" placeholder="请输入样品批号" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="生产日期" prop="productionDate">
                <!-- <el-date-picker
                  v-model="formData.productionDate"
                  type="date"
                  placeholder="选择日期"
                  value-format="YYYY-MM-DD"
                /> -->

                <el-date-picker
                  disabled
                  style="width: 100%"
                  v-model="formData.productionDate"
                  type="date"
                  placeholder="请选择生产日期"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="产品包装" prop="productPackaging">
                <el-input
                  disabled
                  v-model="formData.productPackaging"
                  placeholder="请输入产品包装"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="存放条件" prop="storeCondition">
                <el-input disabled v-model="formData.storeCondition" placeholder="请输入存放条件" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="物资编码" prop="sampleCode">
                <el-input disabled v-model="formData.sampleCode" placeholder="请输入物资编码" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="抽样基数" prop="samplingCardinalNum">
                <el-input
                  disabled
                  v-model="formData.samplingCardinalNum"
                  placeholder="请输入抽样基数"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="抽取样品数量" prop="samplingQuantity">
                <el-input
                  disabled
                  v-model="formData.samplingQuantity"
                  placeholder="请输入抽样数量"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="封样形式" prop="sealedSampleMethod">
                <el-input
                  disabled
                  v-model="formData.sealedSampleMethod"
                  placeholder="请输入封样形式"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="送样方式" prop="deliveryType">
                <el-input disabled v-model="formData.deliveryType" placeholder="请输入送样方式" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="抽样人员" prop="samplingPerson">
                <el-input disabled v-model="formData.samplingPerson" placeholder="请输入抽样人员" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="陪同抽样人" prop="accompanySamplingPerson">
                <el-input
                  disabled
                  v-model="formData.accompanySamplingPerson"
                  placeholder="请输入陪同抽样人"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="受检单位人员" prop="receiveCheckCompanyPerson">
                <el-input
                  disabled
                  v-model="formData.receiveCheckCompanyPerson"
                  placeholder="请输入受检单位人员"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="抽样方式" prop="samplingType">
                <el-select disabled v-model="formData.samplingType" placeholder="请选择抽样方式">
                  <el-option label="委托方自行抽样 " :value="0" />
                  <el-option label="机构自抽自检" :value="1" />
                  <el-option label="第三方抽样" :value="2" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <el-card class="mb-4">
          <template #header>
            <div class="text-lg font-bold">抽样单签字版扫描件、样品照片</div>
          </template>

          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="附件上传" prop="signAndSampleUrl">
                <el-upload
                  action="#"
                  :limit="5"
                  :auto-upload="false"
                  :file-list="fileList"
                  :before-upload="beforeUpload"
                  :on-exceed="handleExceed"
                  :http-request="handleFileChange"
                  :before-remove="beforeRemove"
                  :accept="'image/png, image/jpeg, application/pdf, application/zip'"
                  :on-preview="handlePreview"
                >
                  <!-- <template #tip>
                <div class="el-upload__tip">
                  请上传png、jpg、pdf、zip格式文件。大小不超过50M。
                </div>
              </template> -->
                  <el-button type="primary" disabled>选择文件</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 退样说明
        <el-card class="mb-4">
          <template #header>
            <div class="text-lg font-bold">退样说明</div>
          </template>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="退样方式" prop="returnSampleType">
                <el-radio-group v-model="formData.returnSampleType">
                  <el-radio label="0">不退</el-radio>
                  <el-radio label="1">退</el-radio>
                  <el-radio label="2">部分退</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20" v-if="formData.returnSampleType !=0">
            <el-col :span="8">
              <el-form-item label="退样收货人" prop="returnSampleReceiveBy">
                <el-input v-model="formData.returnSampleReceiveBy" placeholder="请输入退样收货人" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="退样收货地址" prop="returnSampleReceiveAddress">
                <el-input v-model="formData.returnSampleReceiveAddress" placeholder="请输入退样收货地址" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="收货联系方式" prop="returnSampleReceivePhone">
                <el-input v-model="formData.returnSampleReceivePhone" placeholder="请输入收货联系方式" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card> -->

        <!-- 检验要求 -->
        <el-card class="mb-4">
          <template #header>
            <div class="text-lg font-bold">检验要求</div>
          </template>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="检验类型" prop="checkType">
                <el-select disabled v-model="formData.checkType" placeholder="请选择检验类型">
                  <el-option label="委托" :value="1" />
                  <el-option label="监督" :value="2" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="检验时限" prop="checkTimeLimit">
                <el-date-picker
                  disabled
                  v-model="formData.checkTimeLimit"
                  type="date"
                  placeholder="请选择检验时限"
                  value-format="YYYY-MM-DD"
                />

                <!-- <el-date-picker
        v-model="formData.checkTimeLimit"
        type="datetime"
        placeholder="Select date and time"
      /> -->
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="承检机构" prop="inspectionOrg">
                <!-- <el-select v-model="formData.inspectionOrg" placeholder="请选择承检机构">
                  <el-option label="请选择" value="" />
                </el-select> -->
                <el-input disabled v-model="formData.orgName" placeholder="请输入承检机构" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="结果要求" prop="resultRequire">
                <el-radio-group v-model="formData.resultRequire" disabled>
                  <el-radio :label="0">出具检测结果</el-radio>
                  <el-radio :label="1">判定检验结论</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="指标要求" prop="targetRequire">
                <el-radio-group v-model="formData.targetRequire" disabled>
                  <el-radio :label="0">指定检测项目</el-radio>
                  <el-radio :label="1">按照检验依据要求</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="备注" prop="requireRemark">
                <el-input
                  disabled
                  v-model="formData.requireRemark"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入备注"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="附件上传" prop="requireAttachment">
                <el-upload
                  action="#"
                  :limit="5"
                  :auto-upload="false"
                  :file-list="fileList2"
                  :before-upload="beforeUpload"
                  :on-exceed="handleExceed"
                  :http-request="handleFileChange"
                  :before-remove="beforeRemove"
                  :accept="'image/png, image/jpeg, application/pdf, application/zip'"
                  :on-preview="handlePreview"
                >
                  <!-- <template #tip>
                <div class="el-upload__tip">
                  请上传png、jpg、pdf、zip格式文件。大小不超过50M。
                </div>
              </template> -->
                  <el-button type="primary" disabled>选择文件</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 检验信息 -->
        <el-card class="mb-4">
          <template #header>
            <div class="text-lg font-bold">检验信息</div>
          </template>
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="报告编号" prop="reportNum">
                <el-input v-model="formData.reportNum" placeholder="请输入报告编号" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="检测开始日期" prop="checkStartTime">
                <!-- <el-input v-model="formData.projectName" placeholder="请输入样品编号" /> -->
                <el-date-picker
                  v-model="formData.checkStartTime"
                  type="date"
                  placeholder="请选择检测开始日期"
                  value-format="YYYY-MM-DD"
                  style="width: 100%;"
                />

                <!-- <el-date-picker
                  v-model="formData.checkStartTime"
                  type="date"
                  placeholder="选择日期"
                  value-format="YYYY-MM-DD"
                /> -->

                <!-- <el-date-picker
        v-model="formData.checkStartTime"
        type="datetime"
        placeholder="请选择项目起始时间"
        value-format="YYYY-MM-DD HH:mm:ss"
      /> -->
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item  label="检测结束日期" prop="checkEndTime">
                <!-- <el-input v-model="formData.projectName" placeholder="请输入盲样编号" /> -->

                <!-- <el-date-picker
                  v-model="formData.checkEndTime"
                  type="date"
                  placeholder="选择日期"
                  value-format="YYYY-MM-DD"
                /> -->

                <el-date-picker
                  v-model="formData.checkEndTime"
                  type="date"
                  placeholder="请选择检测结束日期"
                  value-format="YYYY-MM-DD"
                  style="width: 100%;"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="报告日期" prop="reportDate">
                <!-- <el-input v-model="formData.projectName" placeholder="请输入盲样编号" /> -->

                <!-- <el-date-picker
                  v-model="formData.checkEndTime"
                  type="date"
                  placeholder="选择日期"
                  value-format="YYYY-MM-DD"
                /> -->

                <el-date-picker
                  v-model="formData.reportDate"
                  type="date"
                  placeholder="请选择报告日期"
                  value-format="YYYY-MM-DD"
                  style="width: 100%;"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="实验室名称" prop="labName">
                <el-input v-model="formData.labName" placeholder="请输入实验室名称" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="主要检测设备" prop="mainCheckDevice">
                <el-input v-model="formData.mainCheckDevice" placeholder="请输入主要检测设备" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="检验状态" prop="checkState">
                <!-- <el-input v-model="formData.projectManager" placeholder="请输入未检查/开始检查/检验完成/重新检验" /> -->
                <el-select
                  disabled
                  v-model="formData.checkState"
                  placeholder="请选择检验状态"
                  clearable
                  style="width: 100%;"
                >
                  <el-option
                    v-for="item of statusList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="检验结论" prop="checkConclusion">
                <el-input v-model="formData.checkConclusion" placeholder="请输入检验结论" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="检验人员" prop="checkPerson">
                <el-input v-model="formData.checkPerson" placeholder="请输入检验人员" />
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="退回原因" prop="projectManager" v-if="formData.checkState == 3">
                <el-input
                  type="textarea"
                  v-model="formData.returnReason"
                  placeholder="请输入退回原因"
                  disabled
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
      </el-form>

      <!-- 检验结果 -->
      <el-card class="mb-4">
        <template #header>
          <div class="flex justify-between items-center">
            <div class="text-lg font-bold">检验结果</div>
            <div>
              <el-button type="primary" @click="handleAdd">新增</el-button>
            </div>
          </div>
        </template>

        <div>
          <el-table :data="tableData" style="width: 100%">
            <el-table-column type="index" label="序号" width="100" />
            <el-table-column prop="checkProject" label="检测项目" />
            <el-table-column prop="unit" label="单位" />
            <el-table-column prop="designRequire" label="设计要求" />
            <el-table-column prop="checkResult" label="检验结果" />
            <el-table-column prop="singleDecision" label="单项判定" />
            <el-table-column prop="executeStandardName" label="执行标准" />
            <el-table-column prop="remark" label="备注" />
            <el-table-column label="操作">
              <template #default="scope">
                <el-button link type="primary" @click="handleEdit(scope.row)">编辑</el-button>
                <el-button link @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>

      <el-card class="mb-4">
        <template #header>
          <div class="text-lg font-bold">检验报告</div>
        </template>

        <el-col :span="24">
          <el-form-item label="附件上传" prop="checkReportUrl">
            <el-upload
              action="#"
              :limit="5"
              :auto-upload="false"
              :file-list="fileList1"
              :before-upload="beforeUpload"
              :on-exceed="handleExceed"
              :http-request="handleFileChange1"
              :before-remove="beforeRemove1"
              :accept="'image/png, image/jpeg, application/pdf, application/zip'"
              :on-preview="handlePreview"
               :on-change="handleFileSelect1"
            >
              <template #tip>
                <div class="el-upload__tip">
                  请上传png、jpg、pdf、zip格式文件。大小不超过50M。
                </div>
              </template>
              <el-button type="primary">选择文件</el-button>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-card>
    </el-card>
  </ContentWrap>

  <el-dialog v-model="dialogVisible" v-if="dialogVisible" title="检验信息" width="700">
    <el-form
      inline
      ref="dialogFromRef"
      :model="dialogFrom"
      :rules="Dialogrules"
      label-width="100px"
    >
      <el-form-item label="检验项目" prop="checkProject">
        <el-input v-model="dialogFrom.checkProject" placeholder="请输入检验项目" />
      </el-form-item>

      <el-form-item label="单位" prop="unit">
        <el-input v-model="dialogFrom.unit" placeholder="请输入单位" />
      </el-form-item>

      <el-form-item label="设计要求" prop="designRequire">
        <el-input v-model="dialogFrom.designRequire" placeholder="请输入设计要求" />
      </el-form-item>

      <el-form-item label="检验结果" prop="checkResult">
        <el-input v-model="dialogFrom.checkResult" placeholder="请输入检验结果" />
      </el-form-item>

      <el-form-item label="单项判定" prop="singleDecision">
        <el-input v-model="dialogFrom.singleDecision" placeholder="请输入单项判定" />
      </el-form-item>

      <el-form-item label="执行标准" prop="executeStandardName">
        <el-autocomplete
          v-model="dialogFrom.executeStandardName"
          :fetch-suggestions="querySearch"
          clearable
          class="inline-input"
          style="width: 197px"
          placeholder="请输入执行标准"
          @select="handleSelect"
          @input="handleInput"
        >
          <template #suffix>
            <i class="iconfont icon-sousuo"></i>
          </template>
        </el-autocomplete>
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input v-model="dialogFrom.remark" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">返回</el-button>
        <el-button type="primary" @click="handleDialog"> 保存 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { SampleInformationApi } from '@/api/qis/sampleinformation'
import { useMessage } from '@/hooks/web/useMessage'
import { Plus } from '@element-plus/icons-vue'
import { visibility } from 'html2canvas/dist/types/css/property-descriptors/visibility'
import { StandardMaintainApi } from '@/api/qis/standardmaintain'
import { getDictDataPage } from '@/api/system/dict/dict.data'
import { pa } from 'element-plus/es/locale'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/store/modules/user'
import { isEqual } from 'lodash-es'
const router = useRouter()
const message = useMessage()
const formRef = ref()

const dialogFrom = ref({})

const dialogFromRef = ref()

const tempFileList1 =ref<any>([])
const handleFileSelect1 = (file: any, fileList: any) => {
  console.log('File selected:', file, fileList)
  if (file.raw) {
    tempFileList1.value.push(file.raw)
    fileList1.value = fileList
  }
}




const uploadFiles1 = async () => {
  // 如果是编辑模式，我们需要检查哪些文件被保留了
  if (formData.value.id) {
    // 获取当前显示的文件URL列表
    const currentFileUrls = fileList1.value
      .filter(file => file.url && file.url.startsWith('http'))
      .map(file => file.url)
    
    // 直接使用这些URL作为checkReportUrl，不需要重新上传已有的文件
    formData.value.checkReportUrl = currentFileUrls.join(';')
  } else {
    // 新增模式，checkReportUrl应该为空
    formData.value.checkReportUrl = ''
  }
  
  // 只上传新添加的文件
  if (tempFileList1.value.length === 0) return true
  try {
    const uploadPromises = tempFileList1.value.map(async (file) => {
      const formData = new FormData()
      formData.append('file', file)
      const res = await SampleInformationApi.uploadFileApi(formData)
      
      return (window.configUrl.minIo?window.configUrl.minIo: 'http://182.151.214.104:8040') + res
    })
    
    const urls = await Promise.all(uploadPromises)
    // 将新上传的URL添加到现有URL中
    const currentUrls = formData.value.checkReportUrl ? 
      formData.value.checkReportUrl.split(';').filter(Boolean) : []
    
      formData.value.checkReportUrl = [...currentUrls, ...urls].join(';')
    tempFileList1.value = []
    console.log('最终保存的附件:', formData.value.checkReportUrl)
    return true
  } catch (error) {
    console.error(error)
    message.error('文件上传失败')
    return false
  }
}

const closeDialog = () => {
  dialogFrom.value = {}

  dialogVisible.value = false
}

const dialogVisible = ref(false)

const route = useRoute()
const id = route.query.id as unknown as Number
const userStore = useUserStore()
const userName = computed(() => userStore.user.nickname ?? 'Admin')

const templateFormData = {
  resultRequire: '0',
  targetRequire: '1',
  checkPerson: userName.value
}

let formData = ref<any>(templateFormData)

const restaurants = ref([])
const querySearch = (queryString: string, cb: any) => {
  const results = queryString
    ? restaurants.value.filter(createFilter(queryString))
    : restaurants.value
  // call callback function to return suggestions
  cb(results)
}

const getBzwhList = async () => {
  console.log('1111')
  const res = await StandardMaintainApi.getStandardMaintainPage({pageNo:1,pageSize:10000})
  restaurants.value = res.list.map((v) => {
    return { value: v.name, id: v.id }
  })
}
const createFilter = (queryString: string) => {
  return (restaurant) => {
    return restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
  }
}

const handleInput = (value)=>{
  console.log(value)
  dialogFrom.value.standardType = 0
  dialogFrom.value.executeStandardName = value
  dialogFrom.value.executeStandard = value
}

const handleSelect = (item) => {
  dialogFrom.value.standardType = 1
  dialogFrom.value.executeStandard = item.id
  dialogFrom.value.executeStandardName = item.value
  console.log(item, 'item')
}

const tableData = ref<any>([])

const fileList = ref<any>([])

const handleDialog = () => {
  dialogFromRef.value.validate(async (valid: any) => {
    if (valid) {
      if (dialogFrom.value.id) {
        await SampleInformationApi.updateCheckResultApi(dialogFrom.value)
        dialogVisible.value = false
      } else {
        dialogFrom.value.sampleId = formData.value.id
        const res = await SampleInformationApi.createCheckResultApi(dialogFrom.value)
        console.log(res)
        dialogVisible.value = false
      }

      getDetail()
    }
  })
}

const statusList = ref([])
// 获取检验状态字典
const getDictDataPageApi = async () => {
  const res = await getDictDataPage({
    dictType: 'check_state'
  })
  console.log(res, 'res')
  statusList.value = res.list.map((v) => {
    console.log(v.value, 'v')
    return {
      label: v.label,
      value: Number(v.value)
    }
  })
  console.log(res, '状态字典')
}

const imgUrl = ref<any>()

// 删除机构资质上传文件
const beforeRemove = (uploadFile, uploadFiles) => {
  fileList.value = fileList.value.filter((item) => {
    return item.uid !== uploadFile.uid
  })
}

// 删除机构资质上传文件
const beforeRemove1 = (uploadFile, uploadFiles) => {
  fileList1.value = fileList1.value.filter((item) => {
    return item.uid !== uploadFile.uid
  })
}

const handlePreview = (file) => {
  console.log(file)
  console.log(file, 'file')
  const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg', 'pdf']
  const fileExtension = file.name.split('.').pop().toLowerCase()
  if (imageExtensions.includes(fileExtension)) {
    // 如果是图片，在新窗口中打开
    window.open(file.url, '_blank')
  } else {
    // 不是图片，进行文件下载
    const a = document.createElement('a')
    const url = file.url
    a.download = file.name
    a.href = url
    a.click()
  }
}

const fileList1 = ref<any>([])

const fileList2 = ref<any>([])

const handleFileChange1 = async (target: any) => {
  const fileDataFile = new FormData()
  fileDataFile.append('file', target.file)

  const res = await SampleInformationApi.uploadFileApi(fileDataFile)
  imgUrl.value = res
  // imgUrl.value = 'http://192.168.2.241:8040' + imgUrl.value

  imgUrl.value = (window.configUrl.minIo?window.configUrl.minIo : 'http://182.151.214.104:8040') + imgUrl.value

  fileList1.value.push({
    uid: target.file.uid, // 生成唯一的 uid
    name: imgUrl.value.split('/').pop(), // 从 URL 中提取文件名
    url: imgUrl.value
  })

  fileList.value.forEach((item,index)=>{
    item.name = '附件' + (index+1)
  })
  message.success('上传成功')
}

const handleFileChange = async (target: any) => {
  const fileDataFile = new FormData()
  fileDataFile.append('file', target.file)

  const res = await SampleInformationApi.uploadFileApi(fileDataFile)
  imgUrl.value = res
  // imgUrl.value = 'http://192.168.2.241:8040' + imgUrl.value
  imgUrl.value = (window.configUrl.minIo?window.configUrl.minIo: 'http://182.151.214.104:8040') + imgUrl.value
  fileList.value.push({
    uid: target.file.uid, // 生成唯一的 uid
    name: imgUrl.value.split('/').pop(), // 从 URL 中提取文件名
    url: imgUrl.value
  })
  message.success('上传成功')
}

// const handleFileChange = async (file: any,fileList) => {
//   console.log(fileList,'fileList')
//   const   current = fileList.map(item => item.url);
// formData.value.signAndSampleUrl = current.join(',')
// //   // console.log(formData.value.signAndSampleUrl,'formData.value.signAndSampleUrl')

// const fileDataFile = new FormData()
// fileDataFile.append('file',file.raw)

// //   fileList2.value = fileList1;
// //   const formDataFile = new FormData();
// //   fileList2.value.forEach((file)=>{
// //     formDataFile.append('file',file)

// //   })

// const res =  await  SampleInformationApi.uploadFileApi(fileDataFile)
// imgUrl.value = res.data
// message.success('上传成功')

// }

// 新增
const handleAdd = () => {
  getBzwhList()
  dialogFrom.value = {}
  dialogFromRef.value?.resetFields()
  dialogVisible.value = true
}

const handleEdit = (row: any) => {

  console.log(row)
  dialogFrom.value = { ...row }

  dialogFrom.value.executeStandardName = row.executeStandardName 
  console.log(row.executeStandardName, 'row.executeStandardName')
  console.log(dialogFrom.value, 'dialogFrom.value')
  // dialogFrom.value.executeStandard = row.executeStandard
  // dialogFrom.value.executeStandardName = row.executeStandardName
  dialogVisible.value = true
  getBzwhList()
}

const handleDelete = async (row: any) => {
  console.log(row)
  try {
    const res = await SampleInformationApi.deleteCheckResultApi(row.id)
    message.success('删除成功')
    // getTableList()
    getDetail()
  } catch (error) {
    message.success('删除失败')
  }
}

const rules = {
  reportNum: [
    { required: true, message: '请输入报告编号', trigger: 'blur' },
    { max: 30, message: '报告编号不能超过30个字符', trigger: 'blur' }
  ],
  checkStartTime: [{ required: true, message: '请选择检测开始日期', trigger: 'change' }],
  checkEndTime: [{ required: true, message: '请选择检测结束日期', trigger: 'change' }],
  reportDate: [{ required: true, message: '请选择报告日期', trigger: 'change' }],
  labName: [
    { required: true, message: '请输入实验室名称', trigger: 'blur' },
    { max: 30, message: '实验室名称不能超过30个字符', trigger: 'blur' },
    {
      max: 30,
      message: '实验室名称长度不能超过30个字符',
      trigger: 'blur'
    }
  ],
  mainCheckDevice: [
    { required: true, message: '请输入主要检测设备', trigger: 'blur' },
    { max: 50, message: '主要检测设备长度不能超过50个字符', trigger: 'blur' }
  ],
  checkConclusion: [
    { required: true, message: '请输入检验结论设备', trigger: 'blur' },
    { max: 30, message: '检验结论不能超过30个字符', trigger: 'blur' }
  ],
  checkPerson: [
    { required: true, message: '请输入检验人员', trigger: 'blur' },
    { max: 10, message: '检验人员不能超过10个字符', trigger: 'blur' }
  ]
}

const Dialogrules = {
  checkProject: [
    { required: true, message: '请输入检验项目', trigger: 'blur' },
    { max: 30, message: '检验项目长度不能超过30个字符', trigger: 'blur' },
  ],
  unit: [
    { required: true, message: '请输入单位', trigger: 'blur' },
    { max: 10, message: '单位不能超过10个字符', trigger: 'blur' },
  ],
  designRequire: [
    { required: true, message: '请输入设计要求', trigger: 'blur' },
    { max: 50, message: '设计要求长度不能超过50个字符', trigger: 'blur' },
  ],
  checkResult: [
    { required: true, message: '请输入检验结果', trigger: 'blur' },
    { max: 30, message: '检验结果长度不能超过30个字符', trigger: 'blur' },
  ],
  // entrustCompany:[{max:10,message:'单位不能超过10个字符',trigger:'blur'}],
  singleDecision: [
    { required: true, message: '请输入单项判定', trigger: 'blur' },
    { max: 50, message: '单项判定不能超过50个字符', trigger: 'blur' },
  ],
  executeStandardName: [
    { required: true, message: '请输入执行标准', trigger: 'blur' },
    { max: 50, message: '执行标准不能超过50个字符', trigger: 'change' },
  ],
  remark: [
    { max: 50, message: '备注长度不能超过50个字符', trigger: 'blur' },
  ]
}

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        await SampleInformationApi.createSampleInformation(formData)
        message.success('送检成功')
        goBack()
      } catch (error) {
        message.error('送检失败')
      }
    }
  })
}

// 文件限制

const beforeUpload = (file, isShowMessage = true) => {
  const baseSize = 50
  // const isAllowedType = ['image/png', 'image/jpeg', 'application/pdf', 'application/zip'].includes(file.type);
  // if (!isAllowedType) {
  //       message.error('请上传png、jpg、pdf、zip格式的文件。');
  //       return false;
  //     }
  const maxSize = baseSize * 1024 * 1024 // 50MB
  if (file.size > maxSize) {
    isShowMessage && message.warning(`文件大小不能超过 ${baseSize}MB`)
    return false
  }

  return true
}

/** 处理文件超出限制 */
const handleExceed = (files: File[], uploadFiles: File[]) => {
  console.log(111)
  message.warning(`最多只能上传 5 个文件，当前已选择了 ${uploadFiles.length} 个文件`)
}

const getDetail = async () => {
  if (id) {
    const res = await SampleInformationApi.getSampleInformation(id as number)
    console.log(res)
    const tempForm = { ...res, checkPerson: res.checkPerson || userName.value }
    if (isEqual(templateFormData, formData.value)) {
      formData.value = tempForm
    }
    formData.value.resultRequire = res.resultRequire
    formData.value.targetRequire = res.targetRequire
    let url = res.signAndSampleUrl
    let url1 = res.checkReportUrl
    let url2 = res.requireAttachment
    tableData.value = res.checkResultList
    fileList.value = (url || '')
      .split(';')
      .map((item,index) => {
        return {
          uid: Math.random().toString(10).slice(3), // 生成唯一的 uid
          name: '附件' +(index+1), // 从 URL 中提取文件名
          url: item
        }
      })
      .filter((item) => item.url)

    fileList1.value = (url1 || '')
      .split(';')
      .map((item,index) => {
        return {
          uid: Math.random().toString(10).slice(3), // 生成唯一的 uid
          name: '附件' +(index+1), // 从 URL 中提取文件名
          url: item
        }
      })
      .filter((item) => item.url)

    fileList2.value = (url2 || '')
      .split(';')
      .map((item,index) => {
        return {
          uid: Math.random().toString(10).slice(3), // 生成唯一的 uid
          name: '附件' +(index+1), // 从 URL 中提取文件名
          url: item
        }
      })
      .filter((item) => item.url)
  }
}

const handleSave = async (status) => {
 const uploadSuccess =  await uploadFiles1()
 console.log(uploadSuccess,'uploadSuccess')
 if (!uploadSuccess) {
          message.error('文件上传失败，请重试')
          return
        }
        console.log(fileList1.value,'fileList1.value')
  // formData.value.signAndSampleUrl = fileList.value.map((item) => item.url || item).join(';')
  // formData.value.checkReportUrl = fileList1.value.map((item) => item.url || item).join(';')
console.log(formData.value.checkReportUrl,'formData.value.checkReportUrl')
  console.log(id)
  if (!formRef.value) return
  await formRef.value.validate(async (valid: boolean) => {

    if (valid) {
      if (id) {
        if (status === 2) {
          ElMessageBox.confirm('确认提交审核吗？提交后无法修改！', '提示信息', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(async () => {
              formData.value.status = status
              const res = await SampleInformationApi.getSampleInformationUpdateCheckInformation(
                formData.value
              )
              message.success('提交审核成功')
              goBack()
            })
            .catch(() => {
              ElMessage({
                type: 'info',
                message: '取消提交审核'
              })
            })
        } else {
          const res = await SampleInformationApi.getSampleInformationUpdateCheckInformation(
            formData.value
          )
          message.success('保存成功')
          goBack()
        }

        // try {
        // const res =   await SampleInformationApi.getSampleInformationUpdateCheckInformation(formData.value)
        //     if(res.data ){
        //       if(status === 1){
        //     message.success('提交审核成功')
        //   }else{
        //     message.success('保存成功')
        //   }
        //     }
        //   goBack()
        // } catch (error) {
        //   if(status === 1){
        //     message.warning('提交审核失败')
        //   }else{
        //     message.warning('保存失败')
        //   }
        // }
      }
    }
  })
}

const goBack = () => {
  router.back()
}

onMounted(() => {
  getDetail()
  if(route.query.id){
    route.meta.title = '编辑检验信息详情'
  }else {
    route.meta.title = '新增检验信息详情'
  }

  getDictDataPageApi()
})
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .title {
    font-size: 16px;
    font-weight: bold;
  }

  .right-button {
    display: flex;
    gap: 10px;
  }
}

.mb-4 {
  margin-bottom: 1rem;
}

.text-lg {
  font-size: 1.125rem;
}

.font-bold {
  font-weight: bold;
}

:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
  line-height: 100px;
}


::v-deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper){
  width: 100%;
}

::v-deep(.el-form--inline .el-form-item ){
  width: 100%;
}
</style>
